import traceback
import subprocess
import argparse

def exec_cmd_poll(cmd):
    '''
    :param cmd_str:To execute a shell commd string
    :return:subprocess.Popen object
    '''
    proc=subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    while proc.poll() is None:
       print('Working ...')
    print('Exit status',proc.poll())
    
def executeCmdStr(cmd):
        try:
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
            (stdout, stderr) = proc.communicate()
        except:
            print(traceback.format_exc())
            return (False,'')
        if proc.returncode != 0:
            print('execute command error {} [{}]'.format(proc.returncode,stderr))
            return (False,'')
        return (True,stdout.strip())
def executeCmd(cmd):
        proc,stdout,stderr = (None,)*3

        print("cmd=[%s]"%(" ".join(map(str,cmd))))
        try:
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            (stdout, stderr) = proc.communicate()
        except:
            msg="cmd=[%s]\n"%(" ".join(map(str,cmd)))
            msg+=traceback.format_exc()
            print( msg)
            return {'status' : False, 'msg' : stderr}

        print("cmd output=[%s]"%stdout.strip())

        if proc.returncode != 0:
            print("execute command error%d"%proc.returncode)
            return {'status' : False, 'msg' : proc.returncode}

        return {'status' : True, 'msg' : stdout.strip()}
if __name__ == "__main__":
	parser = argparse.ArgumentParser('Hello,world')
	parser.add_argument('cmd')
	args = parser.parse_args()
	command=[]
	command.append(args.cmd)
	result=executeCmd(command)
	print result
	print executeCmdStr('ls -l .')
	print exec_cmd_poll(['sleep','0.5'])
